package me.leiusual.sharing.ui.cart.adapter

import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.view_holder_cart_home_parent.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.cartdetail.Cart
import me.leiusual.sharing.api.model.cartdetail.CartX
import me.leiusual.sharing.ui.helper.ItemTouchHelperCallbackImpl

/**
 * author: leiusual
 * create on: 2019-07-27
 * description:
 */
class CartHomeParentViewHolder(
    override val containerView: View,
    recyclerViewPool: RecyclerView.RecycledViewPool,
    private val changeListener: () -> Unit,
    amountListener: (CartX) -> Unit,
    private val deleteListener: (CartX) -> Unit
) : RecyclerView.ViewHolder(containerView), LayoutContainer, View.OnClickListener {

  private lateinit var cart: Cart

  init {
    check_box.setOnClickListener(this)

    recycler_view.setRecycledViewPool(recyclerViewPool)
    recycler_view.adapter = CartHomeChildAdapter(changeListener, amountListener)
    ItemTouchHelper(object : ItemTouchHelperCallbackImpl() {

      override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        // 删除
        val cartHomeChildViewHolder = viewHolder as CartHomeChildViewHolder
        val cartX = cartHomeChildViewHolder.cartX

        val list = cart.cartList as ArrayList
        list.remove(cartX)

        deleteListener(cartX)
      }
    }).attachToRecyclerView(recycler_view)
  }

  fun bind(cart: Cart) {
    this.cart = cart

    if (cart.cartList.isEmpty()) {
      containerView.isVisible = false
    } else {
      containerView.isVisible = true

      // 选中状态
      check_box.isChecked = cart.cartList.find { !it.checked!! } == null

      // 店铺名称
      check_box.text = cart.storeName

      // 运费
      text_view_freight.text = "运费：￥${cart.freight}"

      // 商品列表
      val adapter = recycler_view.adapter as CartHomeChildAdapter
      adapter.submitList(cart.cartList)
    }
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.check_box -> {
        cart.cartList.forEach {
          it.checked = check_box.isChecked
        }
        changeListener()
      }
    }
  }
}